package cn.hpclub.server.controller.admin;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.JFinal;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.model.ReportDailyPageView;
import cn.hpclub.server.util.ExcelLargeDataUtils;
import cn.hpclub.server.util.SystemConfigUtil;

public class PageviewController extends BaseAdminController<ReportDailyPageView>{

    private static final Logger logger     = LoggerFactory.getLogger(PageviewController.class);
    private static final String START_TIME = "startTime";
    private static final String END_TIME   = "endTime";

    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(searchInfo.get(START_TIME) == null || searchInfo.get(END_TIME) == null){
            try{
                setLastWeek(searchInfo);
            }
            catch(ParseException e){
                e.printStackTrace();
            }
        }

        putQueryKeys(searchInfo);

        ReportDailyPageView pv = new ReportDailyPageView();
        findByPageForSearch(pv.getSelect(), pv.getSqlExceptSelect(searchInfo));
        setAttrs(searchInfo);

        render("/admin/pageview_list.tpl");
    }

    private void putQueryKeys(ConcurrentHashMap<String, String> searchInfo){
        // 传递给查看详情接口字段内容
        JSONObject json = new JSONObject();

        String userId = getPara("user_id", null);
        if(null != userId){
            json.put("user_id", userId);
            searchInfo.put("user_id", userId);
        }
        String startTime = getPara("startTime", null);
        if(null != startTime){
            json.put("startTime", startTime);
            searchInfo.put("startTime", startTime);
        }
        String endTime = getPara("endTime", null);
        if(null != endTime){
            json.put("endTime", endTime);
            searchInfo.put("endTime", endTime);
        }
        String city = getPara("city", null);
        if(null != city){
            json.put("city", city);
            searchInfo.put("city", city);
        }

        if(!json.isEmpty()){
            setAttr("keywords", json.toString());
        }
    }

    public void group(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();

        if(searchInfo.get(START_TIME) == null || searchInfo.get(END_TIME) == null){
            try{
                setDateParam(searchInfo);
            }
            catch(ParseException e){
                e.printStackTrace();
            }
        }

        ReportDailyPageView pv = new ReportDailyPageView();
        findByPageForSearch(pv.getSelectEx(searchInfo), pv.getSqlExceptSelectEx(searchInfo));
        setAttrs(searchInfo);

        render("/admin/pageview_group_list.tpl");
    }

    private void setDateParam(ConcurrentHashMap<String, String> searchInfo) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endDate = sdf.format(new java.util.Date());
        Calendar c = Calendar.getInstance();
        c.setTime(sdf.parse(endDate));
        c.add(Calendar.DAY_OF_YEAR, -1); // 前一天
        String endTime = sdf.format(c.getTime());
        c.add(Calendar.MONTH, -1); // 得到前一个月
        String startDate = sdf.format(c.getTime());

        searchInfo.put(START_TIME, startDate); // 默认显示今天一天的数据
        searchInfo.put(END_TIME, endTime);
    }

    private void setLastWeek(ConcurrentHashMap<String, String> searchInfo) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endDate = sdf.format(new java.util.Date());
        Calendar c = Calendar.getInstance();
        c.setTime(sdf.parse(endDate));
        c.add(Calendar.DAY_OF_YEAR, -1); // 前一天
        String endTime = sdf.format(c.getTime());
        c.add(Calendar.DAY_OF_YEAR, -6); // 得到前一个月
        String startDate = sdf.format(c.getTime());

        searchInfo.put(START_TIME, startDate); // 默认显示今天一天的数据
        searchInfo.put(END_TIME, endTime);
    }

    private String getQueryType(ConcurrentHashMap<String, String> searchInfo){
        String type = "1";
        for(Entry<String, String> item : searchInfo.entrySet()){
            if(item.getKey().equals("type")){
                type = item.getValue().toString();
            }
        }

        return type;
    }

    public void exportGroup(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(searchInfo.get(START_TIME) == null || searchInfo.get(END_TIME) == null){
            try{
                setDateParam(searchInfo);
            }
            catch(ParseException e){
                e.printStackTrace();
            }
        }
        ReportDailyPageView pv = new ReportDailyPageView();

        String type = getQueryType(searchInfo);
        if("2".equals(type)){
            exportGroupByCity(pv.getSelectEx(searchInfo), pv.getSqlExceptSelectEx(searchInfo));
        } else{
            exportGroupByUser(pv.getSelectEx(searchInfo), pv.getSqlExceptSelectEx(searchInfo));
        }
    }

    public void exportDetails(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();

        ReportDailyPageView pv = new ReportDailyPageView();

        exportDetails(pv.getSelect(), pv.getSqlExceptSelect(searchInfo));
    }

    private void exportGroupByUser(String select, String exceptSelect){
        String[] headers = null;
        String[] columns = null;

        headers = new String[] { "手机号码", "工号", "用户名称", "城市", "地区", "开始时间 ", "结束时间", "访问次数" };
        columns = new String[] { "telephone", "emp_code", "user_name", "city", "area", "startTime", "endTime",
                "user_login_count" };

        exportExcel(select, exceptSelect, headers, columns);
    }

    private void exportGroupByCity(String select, String exceptSelect){
        String[] headers = null;
        String[] columns = null;

        headers = new String[] { "城市", "开始时间 ", "结束时间", "访问次数" };
        columns = new String[] { "city", "startTime", "endTime", "user_login_count" };

        exportExcel(select, exceptSelect, headers, columns);
    }

    private void exportDetails(String select, String exceptSelect){
        String[] headers = null;
        String[] columns = null;

        headers = new String[] { "手机号码", "工号", "用户名称", "城市", "地区", "模块名称", "访问时间 ", "访问次数" };
        columns = new String[] { "telephone", "emp_code", "user_name", "city", "area", "module_name", "login_time",
                "login_count" };

        exportExcel(select, exceptSelect, headers, columns);
    }

    private void exportExcel(String select, String exceptSelect, String[] headers, String[] columns){
        String name = generateFileName();
        String filePath = getFilePath(name);
        JSONObject jo = null;
        try{
            String exportFileUrl = ExcelLargeDataUtils.exportData(headers, columns, select + exceptSelect, name,
                                                                  filePath);
            jo = createDownloadSuccessJSONObject(exportFileUrl);
        }
        catch(IOException e){
            e.printStackTrace();
            jo = createDownloadErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

    private String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = "政企数据统计报表" + curTime + ".xlsx";
        return fileName;
    }

    private String getFilePath(String name){
        String filePath = JFinal.me().getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR + name);

        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        logger.debug("pageview fileDir = " + fileDir);

        if(!StringUtils.isEmpty(fileDir)){
            filePath = fileDir + "/file/" + name;
        }
        return filePath;
    }

    private JSONObject createDownloadSuccessJSONObject(String exportFileUrl){
        JSONObject jo = new JSONObject();
        jo.put("status", 1);
        jo.put("message", "导出成功，点击下载");
        jo.put("url", exportFileUrl);
        renderJson(jo.toJSONString());
        return jo;
    }

    private JSONObject createDownloadErrorJSONObject(IOException e){
        JSONObject jo = new JSONObject();
        jo.put("status", 0);
        jo.put("message", "导出失败：" + e.getMessage());
        return jo;
    }
}
